package com.lvy.hczn.front.business.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.lvy.hczn.front.business.common.CacheConstants;
import com.lvy.hczn.front.business.common.Constants;
import com.lvy.hczn.front.system.domain.business.GoodsBox;
import com.lvy.hczn.front.business.dto.Param;
import com.lvy.hczn.front.business.dto.SortTaskDto;
import com.lvy.hczn.front.business.service.SortTaskDetailService;
import com.lvy.hczn.front.business.service.SortTaskService;
import com.lvy.hczn.front.business.service.WcsService;
import com.lvy.hczn.front.business.util.ResultUtil;
import com.lvy.hczn.front.common.core.redis.RedisCache;
import com.lvy.hczn.front.common.exception.UtilException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/wcs/sort/")
@RestController
@Slf4j
public class SortTaskController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SortTaskDetailService sortTaskDetailService;

    @Autowired
    private SortTaskService sortTaskService;

    @Autowired
    private WcsService wcsService;

    @ApiOperation(value = "分拣加工任务，按原料分拣", notes = "分拣加工任务，按原料分拣")
    @PostMapping("sortingTask")
    public ResultUtil sortingTask(@RequestBody Param param) {
        try {
            SortTaskDto sortTaskDto = sortTaskService.sortingTask(param.getUpOrDownPolicy().getClientId(), Constants.SORT_TASK_DETAIL_ING, param.getUpOrDownPolicy().getSpuId(), param);
            synchronized (this) {
                /**
                 wcs消息队列存在数量限制，第一次进入分拣页面，响应的时候，会批量出库一波，会存在队列满了，或者同一topic抢不到的情况(wcs目前未达到一次性发只能连续发，同一topic等wcs响应了，再发下一个)
                 响应未抢到，则放回redis，等出库的时候，wcs释放队列，再发出库指令，也抢不到，目前只能刷新页面（离开缓存位会刷新，以及手动刷新分拣页面），进入else方式
                 暂时不考虑定时任务发送指令**/
                Boolean loading = redisCache.getCacheObject(CacheConstants.SORT_TASK_DOWNLOADING);
                if (!loading && sortTaskDto.getReSortDetailList() != null && !sortTaskDto.getReSortDetailList().isEmpty() && param.getBigProduct() == 0) {
                    redisCache.setCacheObject(CacheConstants.SORT_TASK_DOWNLOADING, true);
                    ThreadUtil.execAsync(() -> {
                        try {
                            sortTaskService.downloadBox(param.getUpOrDownPolicy().getClientId(), Constants.SORT_TASK_DETAIL_ING, sortTaskDto);
                        } catch (Exception e) {
                            log.error("分拣下架异常：", e);
                            throw new RuntimeException(e);
                        } finally {
                            redisCache.setCacheObject(CacheConstants.SORT_TASK_DOWNLOADING, false);
                        }
                    });
                }
            }
            return ResultUtil.ok(sortTaskDto);
        } catch (Exception e) {
            log.error("sortingTask:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "根据原料下架货箱", notes = "分拣加工任务")
    @PostMapping("sortBySpu")
    public ResultUtil sortBySpu(@RequestBody Param param) {
        try {
            GoodsBox goodsBox = sortTaskService.sortBySpu(param.getUpOrDownPolicy().getClientId(), Constants.SORT_TASK_DETAIL_WART);
            if (goodsBox == null) {
                return ResultUtil.failed("无相关数据");
            }
            return ResultUtil.ok(goodsBox);
        } catch (Exception e) {
            log.error("sortBySpu:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "校验分拣是否结束，结束则更改状态", notes = "校验分拣是否结束，结束则更改状态")
    @PostMapping("sortDone")
    public ResultUtil sortDone(@RequestBody Param param) {
        try {
            sortTaskService.sortDone(param.getUpOrDownPolicy().getClientId(), Constants.SORT_TASK_STATUS_ING);
            return ResultUtil.ok();
        } catch (Exception e) {
            log.error("sortDone:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }
}
